<?php
session_start();
/*
 * O'My Friends
 * index.php
 * show friends' ranking
 */
$now = time();
error_log("now:".$now);

$lib_dir = dirname(__FILE__).'/lib/';
require_once $lib_dir.'config.php';
require_once $lib_dir.'facebook.php';
require_once $lib_dir.'util.php';
require_once $lib_dir.'friend.php';
require_once $lib_dir.'friends.php';
require_once $lib_dir.'view.php';
require_once $lib_dir.'init.php';
error_log("require_once end:".(time() - $now));
$now = time();

$me = null;

if($session){
    try{
        $me = getOneself($facebook);
        //session is now valid
        $_SESSION['fb_session'] = $session;
    }catch(Exception $e){
        error_log($e);
        if(isset($_SESSION['fb_session'])){
            $_SESSION['fb_session'] = null;
        }
    }
}

error_log("verify session:".(time() - $now));
$now = time();
/*
 * Build up output HTML
 */
//Get Template
error_log("template start:".(time() - $now));
$now = time();
$html = getTemplateHTML("Social Network Graph");
$appletHtml = file_get_contents('./applet/applet.html');
$refreshButton = '<input id="refresh-image" type="image" src="./images/view-refresh.png" value="refresh"/>';

//Replace custom tag with a real value
$html = str_ireplace("[##_LOGINOUT_BUTTON_##]", ($me)? $logout_button : $login_button, $html);
$html = str_ireplace("[##_REFRESH_BUTTON_##]", ($me)? $refreshButton : null, $html);
$html = str_ireplace("[##_FACEBOOK_ASYNC_LOADING_CODE_##]", null , $html);
$html = str_ireplace("[##_AJAX_FUNCTION_##]", ($me) ? "getFriendsAJAX();" : null, $html);
$html = str_ireplace("[##_GRAPH_APPLET_##]", ($me) ? $appletHtml : null , $html);

$html = str_ireplace("[##_QUERY_STRING_##]", isset($_REQUEST['signed_request']) ? "signed_request=".$_REQUEST['signed_request'] : null, $html);

//Link URL for Friendship pages
if(stripos($me['link'], '?')){
    $link = $me['link']."&";
}else {
    $link = $me['link']."?";
}
$html = str_ireplace("[##_MY_LINK_URL_##]", $link, $html);
error_log("template end:".(time() - $now));
$now = time();

if(!ob_start("ob_gzhandler")) ob_start();
print $html;
ob_end_flush();